package oop.ex2.variables;

import java.util.regex.*;

import oop.ex2.main.Main;


public class Variables {
	boolean isFinal=false;
	boolean methodInit=false;
	String name,value;
	varType type;
	boolean hasInitiated=false;
	
	public Variables(String isFinal, String type, String name,String value) throws BadVaraiableException{
		createVar(isFinal, type, name, value);
	}
	
	public Variables(String var) throws BadVaraiableException{
		Pattern patt=Pattern.compile(Main.VAR_REGEX);
		Matcher match=patt.matcher(var);
		if (match.matches()){
			System.out.println(match.groupCount());
			createVar(match.group(1),match.group(2),match.group(3),(match.groupCount()>4)?match.group(5):null);
		}
//		this.isFinal=match.group(1)!=null;
//		try {
//			this.type=varType.valueOf(match.group(2).toUpperCase());
//		} catch (IllegalArgumentException e) {
//			throw new BadVaraiableException("type " + type + "isn't legal");
//		}
//		this.name=match.group(3);
//		if(match.group(4)==null){
//			if(match.group(5)!=null && match.group(6)!=null && match.group(7)!=null){
//				this.value=match.group(6);
//				this.hasChanged=true;
//			}
//		}		
//		checkVar();
	}
	
	private void checkVar() throws BadVaraiableException{
		if (!this.name.matches("_?[a-zA-Z]+\\w*"))
			throw new BadVaraiableException("illegal name");
		if (this.value!=null){
			if(!this.type.getPatt().matcher(this.value).matches())
				if(!this.value.matches("\\s*\\S+\\(\\s*(\\S+)\\s*\\);"))//check if initiate				
					throw new BadVaraiableException("illegal value");
				else
					methodInit=true;
		}
	}
		
	private void createVar(String isFinal, String type, String name,String value) throws BadVaraiableException{
		this.isFinal=isFinal!=null;
		try {
			this.type=varType.valueOf(type.toUpperCase());
		} catch (IllegalArgumentException e) {
			throw new BadVaraiableException("type " + type + "isn't legal");
		}
		this.name=name;
		if((this.value=value)!=null)
				this.hasInitiated=true;
		checkVar();
	}
	
	public varType getType() {
		return type;
	}
	
	public boolean isMethodInit() {
		return methodInit;
	}

	public void setMethodInit(boolean methodInit) {
		this.methodInit = methodInit;
	}
	
	public boolean getMethodInit() {
		return this.methodInit;
	}
	
	public String getValue() {
		return value;
	}
	
	public void setValue(String value) throws BadVaraiableException {
		this.value = value;
		checkVar();
	}
}
